package com.can.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.can.convert.UserConvert;
import com.can.domain.ResponseResult;
import com.can.domain.entity.User;
import com.can.domain.entity.UserRole;
import com.can.domain.vo.PageVO;
import com.can.domain.vo.UserDetailVO;
import com.can.domain.vo.UserInfoVO;
import com.can.enums.AppHttpCodeEnum;
import com.can.exception.SystemException;
import com.can.mapper.UserMapper;
import com.can.service.RoleService;
import com.can.service.UserRoleService;
import com.can.service.UserService;
import com.can.util.SecurityUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(User) 服务实现类
 *
 * @author cancan
 * @since 2023-05-06 14:31:22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;


    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = getById(userId);
        //封装成UserInfoVo,返回
        return ResponseResult.okResult(UserConvert.INSTANCE.convert(user));
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        // 判断用户名是否存在
        if (0 < count(new LambdaQueryWrapper<User>().eq(User::getUserName, user.getUserName()))) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if (!StringUtils.hasText(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getPassword())) {
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getEmail())) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getNickName())) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        // 判断用户名是否存在
        if (0 < count(new LambdaQueryWrapper<User>().eq(User::getUserName, user.getUserName()))) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //...
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存入数据库
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<PageVO> page(Integer pageNum, Integer pageSize, User user) {
        //分页查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(user.getUserName()), User::getUserName, user.getUserName());
        queryWrapper.like(StringUtils.hasText(user.getPhonenumber()), User::getPhonenumber, user.getPhonenumber());
        queryWrapper.eq(StringUtils.hasText(user.getStatus()), User::getStatus, user.getStatus());

        Page<User> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page, queryWrapper);

        //封装数据返回
        PageVO pageVO = new PageVO(UserConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
        return ResponseResult.okResult(pageVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(User insertUser) {
        List<User> userAllList = list();
        List<User> tempUserList;
        // 用户名必须之前未存在，否则提示：用户名已存在
        tempUserList = userAllList.stream().filter(user1 -> user1.getUserName().equals(insertUser.getUserName())).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(tempUserList)) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        // 手机号必须之前未存在，否则提示：手机号已存在
        tempUserList = userAllList.stream().filter(user1 -> user1.getPhonenumber().equals(insertUser.getPhonenumber())).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(tempUserList)) {
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }
        // 邮箱必须之前未存在，否则提示：邮箱已存在
        tempUserList = userAllList.stream().filter(user1 -> user1.getEmail().equals(insertUser.getEmail())).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(tempUserList)) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        // 密码加密
        insertUser.setPassword(passwordEncoder.encode(insertUser.getPassword()));
        save(insertUser);
        List<UserRole> collect = insertUser.getRoleIds().stream().map(roleId -> new UserRole(insertUser.getId(), roleId)).collect(Collectors.toList());
        userRoleService.saveBatch(collect);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(List<Long> ids) {
        removeByIds(ids);
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().in(UserRole::getUserId, ids));
    }

    @Override
    public UserDetailVO get(Long id) {
        // 用户信息
        UserDetailVO userDetailVO = new UserDetailVO();
        UserInfoVO userInfoVO = UserConvert.INSTANCE.convert(getById(id));
        userDetailVO.setUser(userInfoVO);
        // 用户所关联角色ID
        List<UserRole> userRoleList = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, id));
        List<Long> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        userDetailVO.setRoleIds(roleIds);
        // 所有角色
        userDetailVO.setRoles(roleService.list());

        return userDetailVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserInfoVO vo) {
        User user = UserConvert.INSTANCE.convert01(vo);
        updateById(user);

        userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, vo.getId()));
        userRoleService.saveBatch(user.getRoleIds().stream().map(roleId -> new UserRole(vo.getId(), roleId)).collect(Collectors.toList()));
    }
}

